<template>
  <view class="animated fadeIn faster page-bg page-container">
    <view class="nav py-2 nav-container">
      <view class="d-flex d-flex-item d-flex-middle mb-1 px-2">
        <view class="searchBox">
          <text class="iconfont icon-icon_sousuo first-child"></text>
          <input class="px-5 rounded30  font26  bg-fff" v-model="order_no" placeholder="搜索订单编号"
                 placeholder-class="colorhold"/>
          <text
              v-if="order_no"
              class="iconfont icon-jiufuqianbaoicon08 clear-icon color444"
              @click="clearSearch"></text>
        </view>
        <view class="px-2 color598dfc" style="width: 80rpx;" @click="onSearch">
          搜索
        </view>
      </view>

      <view class="d-flex d-flex-middle d-flex-center date-picker-container bg000 mt-2 p-1  colorfff">
        <text class="iconfont icon-icon_sousuo colorfff px-1"></text>
        <picker mode="date" @change="startDateChange">
          <text>{{ start_time || '开始时间' }}</text>
        </picker>
        <text class="colorfff px-1">~</text>
        <picker mode="date" @change="endDateChange">
          <text> {{ end_time || '结束时间' }}</text>
        </picker>
        <text v-if="start_time&& end_time" class="iconfont icon-jiufuqianbaoicon08 main-color ml-1"
              @click="dataCancel"></text>
      </view>


      <view class="d-flex tab-scroll_box px-2">
        <!-- 选项卡类别列表 -->
        <view class="tab-scroll_item d-flex-item" v-for=" (item,index) in tabs" :key="index"
              :class="{'active':isActive==index}" @click="chenked(index)">
          {{ item.name }}
        </view>
      </view>

      <view class="d-flex d-flex-wrap px-2 mt-2">
        <view class="tabList bg-List  rounded20 mr-2 px-2 line-height30 mb-2" v-for=" (item,index) in tabList"
              :key="index" :class="{'activeList':isActiveList==item.id}" @click="chenkedList(item.id)">
          {{ item.name }}
        </view>
      </view>
    </view>

    <view class="scroll-container">
      <scroll-view scroll-y
                   refresher-enabled="true"
                   :refresher-triggered="refreshing"
                   @refresherrefresh="onRefresh"
                   refresher-background="#f5f5f5"
                   class="scroll-area"
      >
        <view v-if="list.length > 0">
          <view class="nav_item bg-fff mx-2 p-2 mb-2 rounded10" v-for="(item,inde) in list" :key="inde+'c'">
            <view class="font30 pb-1 mb-2 line d-flex d-flex-between">
              <text>{{ item.time }}</text>
              <text v-if="item.user_order_status ==0" class="colorf00">等待打手接单</text>
              <text v-if="item.user_order_status ==1" class="colorf00">等待服务</text>
              <text v-if="item.user_order_status ==4" class="color999">服务完成</text>
              <text v-if="item.user_order_status ==2" class="main-color">服务中</text>
              <text v-if="item.user_order_status ==5" class="colorf00">订单取消</text>
            </view>
            <view class="d-flex  ">
              <image :src="item.resource.icon || item.resource.voice_introduce" class="mr-2 img"></image>
              <view class="d-flex-item d-flex ">
                <view class="mb-1 d-flex-item">
                  <view class="font-bold font30 mt-1">{{ item.resource.name }}</view>
                  <!-- 		<view class="text-clamp-two font26 my-1 color999">
                    {{item.resource.name}}</view> -->
                </view>
                <view class="d-flex d-flex-column d-flex-item text-right">
                  <text class="colorf00 font40">
                    <text class="font22">￥</text>
                    {{ item.amount }}
                  </text>
                  <text class="color999 font22 ml-1-5">×1</text>
                </view>
              </view>
            </view>
            <view class="d-flex d-flex-between mt-3 line pb-2">
              <view class="d-flex d-flex-column mr-1">
                <text class="line-height50">订单编号</text>
                <text class="line-height50">游戏名称</text>
                <text class="line-height50">下单时间</text>
                <text class="line-height50">接单时间</text>
                <text class="line-height50">开始服务时间</text>
                <text class="line-height50">完成时间</text>
                <text class="line-height50">确认截止时间</text>
                <text class="line-height50">订单备注</text>
              </view>
              <view class="d-flex d-flex-column d-flex-item">
                <view class="d-flex d-flex-middle line-height50 d-flex-between">
                  <text class="mr-1 color999 font26">{{ item.order_no }}</text>
                  <image style="width: 30rpx;height: 30rpx;"
                         src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/strike.png"
                         @click="copypw(item.order_no)">
                  </image>
                </view>
                <text class="color999 font26 line-height50">{{ formatField(item.resource?.game_name) }}</text>
                <text class="color999 font26 line-height50">{{ formatField(item.created_at) }}</text>
                <text class="color999 font26 line-height50">{{ formatField(item.accept_time) }}</text>
                <text class="color999 font26 line-height50">{{ formatField(item.service_time) }}</text>
                <text class="color999 font26 line-height50">{{ formatField(item.complete_time) }}</text>
                <text class="color999 font26 line-height50">{{ formatField(item.confirmation_deadline) }}</text>
                <text class="color999 font26 ">{{ formatField(item.remark, '无备注') }}</text>
              </view>
            </view>
            <view class="d-flex py-2 d-flex-end d-flex-wrap">
              <view
                    class="bg-fff btn color999 px-3 py-1 rounded30  font26 mr-2"
                    @click="toChat(item.player_id == userId?item.user_id:item.player_id)">联系对方
              </view>
              <view v-if="item.player_order_status ==1 &&item.player_id == userId"
                    class="bg-fff btn color999 px-3 py-1 rounded30  font26 mr-2"
                    @click="goUrl(item,item.user_order_status)">开始服务
              </view>
              <view v-if="item.player_order_status ==2 &&item.player_id == userId"
                    class="bg-fff btn color999 px-3 py-1 rounded30  font26 mr-2"
                    @click="goUrl(item,item.user_order_status)">上传截图
              </view>
              <view v-if="item.user_order_status ==3 && item.user_id == userId"
                    class="bg-fff btn color999 px-3 py-1 rounded30  font26 mr-2"
                    @click="goUrl(item,item.user_order_status)">用户确认
              </view>
              <!--我下的单-->
              <view
                  v-if="item.user_id == userId &&  item.user_order_status ==1 || item.user_id == userId &&item.user_order_status ==0"
                  class="bg-fff btn color999 px-3 py-1 rounded30  font26 mr-2"
                  @click="goUrl(item,4)">取消订单
              </view>


              <button class="font26 colorfff fix-button d-flex d-flex-center d-flex-middle rounded50 wmBtnBg"
                      :open-type="loginState?'contact': ''" @click="loginState? '':goUrl()">
                联系客服
              </button>
            </view>
          </view>
        </view>

        <view class="load-more d-flex d-flex-center d-flex-column d-flex-middle py-4"
              v-if="loadingType >= 1 && list.length == 0">
          <image
              src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/empty.png"
              style="width: 198rpx;height: 128rpx;margin-top: 260rpx;"></image>
          <text class="empty-text">{{ loadingType === 1 ? '正在加载...' : '~ 暂无相关订单 ~' }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 使用 uni-popup 的上传截图弹窗 -->
    <uni-popup ref="uploadPopup" type="center" :mask-click="false">
      <view class="upload-popup">
        <view class="popup-header">
          <text class="popup-title">上传截图</text>
          <text class="popup-close" @click="closeUploadPopup">×</text>
        </view>
        <view class="popup-body">
          <uni-file-picker limit="1" v-model="imgList" :auto-upload="false" @select="handleSelect"
                           :source-type="['album', 'camera']"></uni-file-picker>
          <view class="order-info mt-2" v-if="currentOrder">
            <text class="info-label">订单编号:</text>
            <text class="info-value">{{ currentOrder.order_no }}</text>
          </view>
        </view>

        <view class="popup-footer">
          <button class="btn-cancel" @click="closeUploadPopup">取消</button>
          <button class="btn-confirm" @click="submitScreenshot">上传</button>
        </view>
      </view>
    </uni-popup>


  </view>
</template>
<script>
import {
  payApi
} from '@/http/payApi';
import {fileApi} from '@/http/fileApi.js';
import {userApi} from '@/http/userApi.js';
import {
  mapState
} from "vuex"
import store from '@/store';

export default {
  data() {
    return {
      isActive: 0,
      index: 0,
      currentindex: 0,
      tabs: [{
        name: '全部',
      },
        {
          name: '我下的单',
        },
        {
          name: '我接的单',
        }
      ],
      user_order_list: [
        {
          id: -1,
          name: '全部',
        },
        {
          id: 0,
          name: '待接单',
        },
        {
          id: 1,
          name: '待服务',
        },
        {
          id: 2,
          name: '服务中',
        },
        {
          id: 3,
          name: '已完成',
        },
        {
          id: 4,
          name: '已确认',
        },
        {
          id: 5,
          name: '取消订单',
        },
        {
          id: 6,
          name: '系统完成订单',
        },
        {
          id: 7,
          name: '系统退单',
        }
      ],
      user_order_status: '',
      player_order_status: '',
      player_order_list: [
        {
          id: -1,
          name: '全部',
        },
        {
          id: 1,
          name: '待服务',
        },
        {
          id: 2,
          name: '服务中',
        },
        {
          id: 3,
          name: '待确认',
        },
        {
          id: 4,
          name: '已完成',
        },
        {
          id: 5,
          name: '被取消订单',
        },
        {
          id: 6,
          name: '系统完成订单',
        },
        {
          id: 7,
          name: '系统退单',
        }
      ],
      start_time: '',
      end_time: '',
      list: [],
      tabList: [],
      isActiveList: 0,
      order_no: '',
      currentDate: '',
      scrollViewHeight: '1120rpx',
      uploadImage: '', // 上传的图片路径
      currentOrder: null, // 当前操作的订单
      imgList: [],
      refreshing: false, // 下拉刷新状态
      orderType: '',
      loadingType: 1,
      page: 1
    }
  },

  onLoad(option) {
    if (option.order_type) {
      this.isActive = Number(option.order_type)
      if (this.isActive == 2) {
        if (option.player_order_status) {
          this.isActiveList = Number(option.player_order_status)
          this.player_order_status = Number(option.player_order_status)
        } else {
          this.isActiveList = 0
          this.player_order_status = ''
        }

      } else if (this.isActive == 1) {
        if (option.user_order_status) {
          this.isActiveList = Number(option.user_order_status)
          this.user_order_status = Number(option.user_order_status)
        } else {
          this.isActiveList = 0
          this.user_order_status = ''
        }

      }
      this.orderSee(this.isActive)
      this.checkedIndex(this.isActive)
    } else {
      this.orderSee()
    }
  },
  computed: {
    ...mapState({
      loginState: state => state.loginState,
      userId: state => state.id
    })
  },
  methods: {
    toChat(cid) {
      uni.navigateTo({
        url: '/uni_modules/uni-im/pages/chat/chat?user_id=' + cid,
        animationDuration: 300
      })
    },
    async orderSee(order_type) {
      if (order_type == 0 || order_type == undefined) order_type = ''

      // 只有在第一页时才清空列表（这个判断可以根据您的具体需求调整）
      if (this.page === 1) {
        this.list = []
      }

      this.loadingType = 1

      try {
        let params = {
          page: this.page,
          order_type: order_type,
          user_order_status: this.user_order_status,
          player_order_status: this.player_order_status,
          start_time: this.start_time,
          end_time: this.end_time,
          order_no: this.order_no
        }
        let result = await payApi.getOrderSee(params)
        if (result.data) {
          // 如果是第一页，直接赋值；否则追加数据
          if (this.page === 1) {
            this.list = result.data
          } else {
            this.list = this.list.concat(result.data)
          }
        }
        if (result.data && result.data.length > 9) {
          this.loadingType = 0
        } else {
          this.loadingType = 2
        }
      } catch (error) {
        // 出错时如果列表为空，设置为无数据状态
        if (this.list.length === 0) {
          this.loadingType = 2
        }
      }
    },
    chenked(index) {
      console.log(index, 'index')
      this.isActive = index
      this.isActiveList = -1;
      this.user_order_status = '';
      this.player_order_status = ''
      this.page = 1
      this.list = []
      this.checkedIndex(index)
      this.orderSee(index)
    },
    checkedIndex(index) {
      if (index == 1) {
        this.tabList = this.user_order_list
      } else if (index == 2) {
        this.tabList = this.player_order_list
      } else {
        this.tabList = []
      }
    },
    chenkedList(id) {
      this.isActiveList = id
      if (id == -1) {
        this.user_order_status = ''
        this.player_order_status = ''
      } else {
        if (this.isActive == 1) {
          this.user_order_status = id
        }
        if (this.isActive == 2) {
          this.player_order_status = id
        }
      }

      this.page = 1
      this.list = []
      setTimeout(() => {
        this.orderSee(this.isActive)
      }, 1500)
    },
    change(e) {
      const {
        current
      } = e.detail;
      this.currentindex = current;
    },
    copypw(item) {
      uni.setClipboardData({
        data: `${item}`,
        success: function () {
          uni.showToast({
            title: '复制成功',
            icon: 'none'
          })
        }
      })
    },
    // 新增开始日期选择处理
    startDateChange(e) {
      this.start_time = e.detail.value;
      // 如果开始时间和结束时间都已选择，则自动查询
      if (this.start_time && this.end_time) {
        this.page = 1
        this.list = [] // 日期筛选时清空列表
        this.orderSee(this.isActive);
      }
    },
// 新增结束日期选择处理
    endDateChange(e) {
      this.end_time = e.detail.value;
      // 如果开始时间和结束时间都已选择，则自动查询
      if (this.start_time && this.end_time) {
        this.page = 1
        this.list = [] // 日期筛选时清空列表
        this.orderSee(this.isActive);
      }
    },
    dataCancel() {
      this.end_time = ''
      this.start_time = ''
      this.page = 1
      this.list = [] // 取消日期筛选时清空列表
      this.orderSee(this.isActive);
    },
    handleSelect(e) {
      const fileList = e.tempFiles;
      if (fileList.length > 0) {
        const filePath = fileList[0].path;
        this.uploadFile(filePath);
      }
    },
    uploadFile(filePath) {
      let that = this
      uni.showLoading({
        title: '上传中...'
      })
      fileApi.upload(filePath, {'user_id': that.id}).then((res) => {
        uni.hideLoading()
        if (res && res.data) {
          that.imgList.push({'url': res.data, 'name': ''})
        }
      }).catch(() => {
        uni.hideLoading()
      })
    },
    uploadScreenshot(order) {
      this.currentOrder = order;
      this.$refs.uploadPopup.open('center');
    },

    // 关闭弹窗
    closeUploadPopup() {
      this.$refs.uploadPopup.close();
      this.imgList = [];
      this.currentOrder = null;
    },

    // 优化 submitScreenshot 方法
    async submitScreenshot() {
      if (this.imgList.length < 1) {
        uni.showToast({
          title: '请先选择图片',
          icon: 'none'
        });
        return;
      }

      uni.showLoading({
        title: '上传中...'
      });

      try {
        // 使用已有的 screenshot API 上传截图
        const res = await payApi.screenshot({
          image: this.imgList[0].url,
          order_no: this.currentOrder.order_no
        });
        uni.hideLoading();
        this.closeUploadPopup();
        this.orderSee(this.isActive); // 刷新订单列表
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        });
      }
    },
    async goUrl(data, index) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }, 1500)
      } else {
        switch (index) {
          case 1:
            // 开始服务
            try {
              let res = await payApi.handStart({
                order_no: data.order_no
              })
              await this.orderSee(this.isActive)
            } catch (error) {
              uni.showToast({
                title: error.msg,
                icon: 'none'
              })
            }
            break;
          case 2:
            // 上传截图
            this.uploadScreenshot(data);
            break;
          case 3:
            // 待确认
            try {
              let res3 = await payApi.complete({
                order_no: data.order_no
              })
              this.orderSee(this.isActive)
            } catch (error) {
              uni.showToast({
                title: error.msg,
                icon: 'none'
              })
            }
            break;
          case 4:
            // 取消订单
            try {
              let res = await payApi.handCancel({
                order_no: data.order_no
              })
              this.orderSee(this.isActive)

              // 更新用户信息
              try {
                const userData = await userApi.getUserInfo();
                store.commit('setUserInfo', userData);
              } catch (userInfoError) {
                console.error('获取用户信息失败:', userInfoError);
                // 用户信息更新失败不应该影响订单取消操作的结果
              }
              uni.showToast({
                title: '订单取消成功',
                icon: 'success'
              });
            } catch (error) {
              uni.showToast({
                title: error.msg,
                icon: 'none'
              })
            }

            break;
        }

      }
    },
    formatField(date) {
      if (!date) return '-';
      return date; // 或使用具体的时间格式化逻辑
    },
    // 下拉刷新处理
    async onRefresh() {
      if (this.refreshing) return;

      this.refreshing = true;
      this.loadingType = 1; // 设置加载状态
      this.list = [];
      try {
        await this.orderSee(this.isActive);
      } catch (error) {
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      } finally {
        this.refreshing = false;
        if (this.list.length === 0) {
          this.loadingType = 2; // 确保无数据时显示正确状态
        }
      }
    },
    // 重新加载数据方法
    async reloadData() {
      try {
        await this.orderSee(this.isActive);
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    },
    onSearch() {
      this.page = 1
      this.list = [] // 搜索时清空列表
      this.orderSee(this.isActive);
    },
    clearSearch() {
      this.order_no = '';
      this.page = 1;
      this.list = [];
      // 清除搜索后自动刷新列表
      this.orderSee(this.isActive);
    },
  }
}
</script>
<style scoped>
.bg000 {
  background: rgba(89, 141, 252, 0.2);
}

.searchBox {
  position: relative;
  width: 100%;
}

.searchBox input {
  height: 56rpx;
  line-height: 56rpx;
}

.searchBox .first-child {
  position: absolute;
  left: 13rpx;
  top: 12rpx;
}

.line {
  border-bottom: 2rpx solid #EEEEEE;
}

.btn {
  border: 2rpx solid #dcdcdc;
  color: #666;
}

.btn:hover .btn:active {
  background-color: #598dfc;
  color: #fff;
}

.nav {
  align-items: center;
}


.tab-scroll_box {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  box-sizing: border-box;

}

.tab-scroll_item {
  line-height: 60rpx;
  flex-shrink: 0;
  padding-bottom: 10px;
  display: flex;
  justify-content: center;
  font-size: 16px;
  padding-top: 10px;
}


.nav_item .img {
  width: 120rpx;
  height: 120rpx;
}

.active {
  position: relative;
  color: #598dfc;
  font-weight: 600;
}

.active::after {
  content: "";
  position: absolute;
  width: 50rpx; /* 固定宽度，可根据需要调整 */
  height: 4rpx;
  background-color: #598dfc;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%); /* 水平居中 */
}


.bgcolor598dfc {
  background-color: #598dfc;
  color: #fff;
}

.tabList {
  padding-top: 6rpx;
  padding-bottom: 6rpx;
}

.bg-List {
  color: #598dfc;
  background: rgba(0, 0, 252, 0.1);
}

.activeList {
  color: #999;
  background: #fff;
}

/* 上传截图弹窗样式 */
.upload-popup {
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
  padding: 10rpx;
}

.popup-body {
  padding: 30rpx;
}


.order-info {
  display: flex;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.info-label {
  color: #666;
  margin-right: 10rpx;
}

.info-value {
  color: #333;
  font-weight: bold;
}

.popup-footer {
  display: flex;
  border-top: 2rpx solid #eee;
}

.popup-footer button {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border: none;
  outline: none;
  background: none;
  font-size: 30rpx;
}

.btn-cancel {
  color: #666;
  border-right: 2rpx solid #eee;
}

.btn-confirm {
  color: #598dfc;
  font-weight: bold;
}

.wmBtnBg {
  margin-right: 0;
  margin-left: 0;
  background: linear-gradient(45deg, #87adff, #598dfc);
}

.clear-icon {
  position: absolute;
  right: 13rpx;
  top: 12rpx;
  z-index: 999;
}

.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.nav-container {
  flex-shrink: 0; /* 防止收缩 */
}

.scroll-container {
  flex: 1; /* 占据剩余空间 */
  overflow: hidden;
}

.scroll-area {
  height: 100%;
  width: 100%;
}


</style>